package com.weeho.dongyong.exception;

import com.weeho.dongyong.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理器
 * Created by xiejh on 2016/11/2.
 */
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        exceptionHandler(e);
        return Result.exception("服务器异常");
    }

    /**
     * 处理异常
     *
     * @param throwable
     */
    protected void exceptionHandler(Throwable throwable) {
        if (null != throwable) {
            logger.error("error caught: " + throwable.getMessage(), throwable);
        } else {
            logger.error("unknown error caught in RESTController, {}");
        }
    }
}
